package cool.taomu.box.storage.indexed.impl

import cool.taomu.box.guice.ann.Binder
import cool.taomu.box.guice.entity.Scope
import cool.taomu.box.storage.indexed.abs.AbsIndexed
import cool.taomu.box.storage.indexed.inter.IIndexed
import cool.taomu.box.storage.inter.IStorage
import cool.taomu.box.storage.lmdb.LmdbDataSource
import cool.taomu.box.storage.lmdb.LmdbProvider
import cool.taomu.box.storage.lmdb.LmdbUtils
import java.util.Objects
import java.util.concurrent.ConcurrentSkipListMap
import java.util.concurrent.atomic.AtomicLong
import javax.inject.Inject

@Binder(bind=LmdbDataSource,to=LmdbProvider)
@Binder(bind=IStorage,to=LmdbUtils,in=Scope.SINGLETON)
@Binder(bind=IIndexed,to=LmdbIndexed,in=Scope.SINGLETON)
class LmdbIndexed extends AbsIndexed {
	val static keyPathMap = new ConcurrentSkipListMap<String, String>();
	var index = new AtomicLong(0);	
	@Inject
	IStorage lmdb;
	String name;

	override open(String name) {
		this.name = name;
	}
	
	override open(String name, String version) {
		this.name = #[name,version].join("@")
	}
	
	override createKeyPath(String id) {
		Objects.requireNonNull(this.name);
		keyPathMap.put(this.name, id);
	}
	
	override createIndex(String fieldName, boolean unique) {
		throw new UnsupportedOperationException("TODO: auto-generated method stub")
	}
	
	override get(String key) {
		Objects.requireNonNull(this.name);
		return new String(this.lmdb.get(this.name,key));
	}
	
	override put(String result) {
		Objects.requireNonNull(this.name);	
		var String keyPath;
		if (keyPathMap.containsKey(this.name)) {
			keyPath = this.getKeyPath(keyPathMap.get(this.name), result) as String;
		} else {
			keyPath = String.valueOf(index.incrementAndGet);
		}
		this.lmdb.put(this.name,keyPath,result.bytes)
	}

	
	override remove(String key) {
		Objects.requireNonNull(this.name);
		this.lmdb.remove(this.name,key);
	}
	
	override clear() {
		throw new UnsupportedOperationException("TODO: auto-generated method stub")
	}
	
}